<template>
  <div class="mine">
    <van-nav-bar
      title="小博中心"
      left-text="首页"
      @click-left="onClickLeft"
    >
      <template #left>
        <van-icon name="home-o" size="18" />
      </template>
    </van-nav-bar>
    <div class="content">
      <van-form @failed="onFailed" @submit="onSubmit">
        <van-cell-group inset>
          <!-- 通过 pattern 进行正则校验 -->
          <div class="phone">
            <van-field
              v-model="userName"
              name="pattern"
              label="手机号"
              placeholder="请输入手机号"
              :rules="[{ pattern, message: '请输入正确手机号' }]"
            />
            <!-- <span @click="getCode">获取验证码</span> -->
          </div>
          <!-- <van-field
            v-model="password"
            label="验证码"
            name="validator"
            placeholder="请输入验证码"
            :rules="[{ validator, message: '长度在6-18之间，只能包含字符、数字和下划线' }]"
          /> -->
          <!-- 通过 validator 进行函数校验 -->
          <van-field
          v-if="isRegiste"
            v-model="nickName"
            label="昵称"
            name="validator"
            placeholder="请输入密码"
            :rules="[{ validator:validatorNickName, message: '长度在1-18之间,不能输入特殊字符' }]"
          />
          <!-- 通过 validator 进行函数校验 -->
          <van-field
            v-model="password"
            label="密码"
            name="validator"
            placeholder="请输入密码"
            :rules="[{ validator, message: '长度在6-18之间，只能包含字符、数字和下划线' }]"
          />
        </van-cell-group>
        <div style="margin: 16px;">
          <van-button round block type="danger" native-type="submit">{{isRegiste?'注册':'登录'}}</van-button>
          <div class="btn">
            <div>
              <span>其他方式登录</span>
              <a href="https://github.com/login/oauth/authorize?client_id=3a993d4f456065054581&redirect_uri=http://localhost:8080/#/login">gitHub登录</a>
            </div>
            <div>
              <span v-if="!isRegiste" @click="isRegiste=true">进行注册</span>
              <span v-if="isRegiste" @click="isRegiste=false">去登录</span>
            </div>
          </div>
        </div>
      </van-form>
    </div>
  </div>
</template>
<script>
import {getCurrentInstance,ref} from 'vue'
import {useRoute,useRouter} from 'vue-router'
import { Toast } from 'vant';
export default {
  setup() {
    // 获取全局变量得到$axios
    const {proxy} = getCurrentInstance()
    // 表单信息
    const userName = ref('');
    const password = ref('');
    const nickName = ref('');
    const pattern = /^\d{11}$/;
    // 校验函数返回 true 表示校验通过，false 表示不通过 
    const validator = (val) => /^\w{5,17}$/.test(val);
    const validatorNickName = (val) => !(/[`~!@#$%^&*()_+<>?:"{};'[\]]/im).test(val)&&!(/[·！#￥（——）：；“”‘、，|《。》？、【】[\]]/im).test(val)
    // 验证失败
    const onFailed = (errorInfo) => {
      console.log('failed', errorInfo);
    };
    // 路由
    const router = useRouter()
    // 登录
    function login(){
      let data = {
        userName:userName.value,
        password:password.value,
      }
      proxy.$axios.post('/login',data).then(res=>{
        if(res.code=='200'){
          // 未注册的情况
          if(!res.data){
            Toast.fail(res.message);
          }else{
            localStorage.setItem('userInfo',JSON.stringify(res.data))
            localStorage.setItem('token',JSON.stringify(res.data.token))
            router.push('/mine')
          }
        }else{
          Toast.fail(res.message);
        }
      }).catch(err=>{
        console.log(err);
      })
    }
    // 注册
    function registe(){
      let data = {
        userName:userName.value,
        nickName:nickName.value,
        password:password.value,
      }
      proxy.$axios.post('/registe',data).then(res=>{
        if(res.code=='200'){
          // 未注册的情况
          if(!res.data){
            Toast.fail(res.message);
          }else{
            Toast.success('注册成功请进行登录');
          }
        }else{
          Toast.fail(res.message);
        }
      }).catch(err=>{
        console.log(err);
      })
    }
    const onSubmit = (values) => {
      console.log('submit', values);
      if(isRegiste.value){
        registe()
      }else{
        login()
      }
      
    };
    //请求token
    function getUserInfo(){
      proxy.$axios.get(`/oauth?code=${route.query.code}`).then(res=>{
        if(res.code=='200'){
          // console.log(res.data);
          localStorage.setItem('userInfo',JSON.stringify(res.data))
          localStorage.setItem('token',JSON.stringify(res.data.token))
          router.push('/mine')
        }else{
          Toast.fail(res.data);
        }
      }).catch(err=>{
        console.log(err);
      })
    }
    // 获得路由信息
    const route = useRoute()
    if(route.query.code){
      getUserInfo();
    }
    // 登录/注册
    const isRegiste = ref(false)
    // 获取验证码
    function getCode(){
      proxy.$axios.get(`/sms?mobile=${userName.value}`).then(res=>{
        if(res.code=='200'){
          // 未注册的情况
          if(!res.data){
            Toast.fail(res.message);
          }else{
            console.log(res.data);
          }
        }else{
          Toast.fail(res.message);
        }
      }).catch(err=>{
        console.log(err);
      })
    }
    return{
      userName,
      password,
      nickName,
      pattern,
      onFailed,
      validator,
      validatorNickName,
      onSubmit,
      isRegiste,
      getCode,
    }
  }
}
</script>
<style lang="less" scoped>
.mine{
  .content{
    padding: 20px;
    box-sizing: border-box;
    margin-top: 50%;
    .phone{
      display: flex;
      align-items: center;
      white-space: nowrap;
      padding-right: 10px;
      box-sizing: border-box;
    }
    .btn{
      display: flex;
      justify-content: space-between;
      height: 70px;
      // border: 0 solid #DD1A21;
      border-radius: 5px;
      // background-color: #DD1A21;
      align-items: center;
      text-align: center;
      font-size: 20px;
      a{
        margin-left: 16px;
      }
    }
    
  }
}
</style>